/**
 *
 */
package com.tc.dispatch.web.schedule.cost;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import com.tc.dispatch.gsalgorithm.spec.fangkuai;
import com.tc.dispatch.gsalgorithm.spec.parse;
import com.tc.dispatch.gsalgorithm.spec.spec;
import com.tc.dispatch.gsalgorithm.spec.specConst;
import com.tc.dispatch.gsservice.action.GSCalcAction;
import com.tc.dispatch.gsservice.action.GSCalcActionImp;
import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.gsservice.exception.GSException;
import com.tc.dispatch.gsservice.filter.SimpleGSFilter;
import com.tc.dispatch.gsservice.filter.ZQXFilter;
import com.tc.dispatch.gsservice.model.OrderSumSub;
import com.tc.dispatch.gsservice.model.OtherConstants;
import com.tc.dispatch.gsservice.model.OutProcess;
import com.tc.dispatch.gsservice.model.ProcessFee;
import com.tc.dispatch.gsservice.model.ProcessStep;
import com.tc.dispatch.csservice.ejb.CSServiceLocal;
import com.tc.dispatch.csservice.exception.CSException;
import com.tc.dispatch.csservice.model.ManuCost;
import com.tc.dispatch.csservice.model.ProcsDetail;
import com.tc.dispatch.web.csservice.csHelper;
import com.tc.dispatch.web.gsservice.gsHelper;
import com.tc.dispatch.web.util.DateJsonValueProcessor;
import com.tc.dispatch.web.util.FloatJsonValueProcessor;

/**
 * @author cajeep
 *
 */
public class DetailPrice extends HttpServlet {


	/**
	 * Constructor of the object.
	 */
	public DetailPrice() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public boolean updateManuCost(ManuCost mc)
	{
		CSServiceLocal css  = csHelper.getCSServiceLocal();
		GSServiceLocal gsservicelocal=gsHelper.getGSServiceLocal() ;
		try{
			//mc=new ManuCost();
			css.updateManuCost(mc);
			return true;
			}
			catch(CSException e)
			{
				System.out.println("updateManuCost:"+e.getMessage());
				return false;
			}
	}
	public boolean createProcsDetail(ManuCost mc,int schemeId)
	{
		CSServiceLocal css  = csHelper.getCSServiceLocal();
		GSServiceLocal gss=gsHelper.getGSServiceLocal() ;
		try{
			List psList = gss.findProcessStep(" where specName='"
					+ mc.getSpecType() + "' and scheme="
					+ schemeId);
			Iterator it = psList.iterator();
			List subList = new ArrayList();
			GSCalcAction gsca = gss.getGSCalc();
			int linenum=1;
			while (it.hasNext()) {
				ProcessStep ps = (ProcessStep) it.next();
				ProcsDetail oss = new ProcsDetail();
				oss.setDanjia(new Float(0));
				oss.setJiage(new Float(0));
				oss.setLinenum(linenum++);
				oss.setMianji(new Float(0));
				oss.setPerqty(new Float(1));
				oss.setTisheng(new Float(1));
				oss.setTransnum(mc.getTransnum());
				oss.setType(ps.getProcessName());
				oss.setPecent1(new Float(100));


				css.createProcsDetail(oss);
			}
		}
		catch(GSException gse)
		{
			System.out.println("GSException is found in createProcsDetail:"+gse.getMessage());
			return false;
		}
		catch(CSException e)
		{
			System.out.println("CSException is found in createProcsDetail:"+e.getMessage());
			return false;
		}
		return true;

	}
	public int saveProcess(ProcsDetail pd)
	{
		CSServiceLocal css  = csHelper.getCSServiceLocal();
		GSServiceLocal gsservicelocal=gsHelper.getGSServiceLocal() ;
		try{
		css.createProcsDetail(pd);
		}
		catch(CSException e)
		{
			System.out.println("saveProcess:"+e.getMessage());
			return 0;
		}
		return pd.getLinenum();
	}
	public boolean updateProcess(ProcsDetail pd)
	{

		CSServiceLocal css  = csHelper.getCSServiceLocal();
		GSServiceLocal gsservicelocal=gsHelper.getGSServiceLocal() ;
		try{
		css.updateProcsDetail(pd);
		}
		catch(CSException e)
		{
			System.out.println("updateProcess:"+e.getMessage());
			return false;
		}
		return true;
	}
	public boolean removeProcess(ProcsDetail pd)
	{


		CSServiceLocal css  = csHelper.getCSServiceLocal();
		GSServiceLocal gsservicelocal=gsHelper.getGSServiceLocal() ;
		try {
			css.removeProcsDetail(pd);
		} catch (CSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public ProcsDetail calcProcsDetail(String kaimo,ProcsDetail pd,String finalSpec)
	{
		/** TODO
		 * 	需要配置加工后的规格,读取加工成品率，读取加工费，读取加工面积，读取加工件数。
		 */
		CSServiceLocal css  = csHelper.getCSServiceLocal();
		GSServiceLocal gss=gsHelper.getGSServiceLocal() ;
		GSCalcAction gsc=gss.getGSCalc();
		spec before;

		before=parse.parseSpec(kaimo);
		String after=gsc.gsAfterSpec(before,parse.parseSpec(finalSpec) , pd.getType());
		spec afterSpec=parse.parseSpec(after);
		String type=afterSpec.sort();
		String whereStr="";
		if(type.equals(specConst.YuanZhu)||type.equals(specConst.TaoKong))
			type=specConst.YuanZhu;

		else
			type=specConst.Fangkuai;
			whereStr=" where name='"+pd.getType()+"默认成品率'";
		try{
			List ret=gss.findOtherConstants(whereStr);
			OtherConstants oc=new OtherConstants();
			if(ret.size()>1)
			{
				Iterator it=ret.iterator();
				while(it.hasNext())
				{
					OtherConstants temp=(OtherConstants)it.next();
					if(temp.getSpecType().equals(type))
					{
						oc=temp;
						break;
					}
				}

			}
			else
				oc=(OtherConstants)ret.get(0);
			Float yield =oc.getConstant();


		Float area=gss.getProcessArea(" where beforeType='"+before.sort()+"' and afterType='"+afterSpec.sort()+"' and processName='"+pd.getType()+"'", afterSpec,before);

		ProcessFee pf=gss.getProcessFee(" where specType='"+afterSpec.sort()+"' and processName='"+pd.getType()+"'", afterSpec);
		Float fee=new Float(0);
		if(pf!=null)
			fee=pf.getPrice();
		OutProcess op=gss.getKnife(before.sort(), before,new SimpleGSFilter() );

		Integer qieNum=gsc.gsQieNum(before, afterSpec,new fangkuai(), pd.getType(), op.getKnIn(), op.getKnOut());

		pd.setMianji(area);
		pd.setDanjia(fee);
		pd.setSpec(afterSpec.getspec());
		pd.setPecent1(yield);
		pd.setPerqty(new Float(qieNum.intValue()));
		return pd;
		}
		catch(GSException gse)
		{
			System.out.println("GSException is found in calcProcsDetail:"+gse.getMessage());
			return pd;
		}

	}


	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to
	 * post.
	 *
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		if (action == null)
			action = "";

		CSServiceLocal css  = csHelper.getCSServiceLocal();
		GSServiceLocal gss=gsHelper.getGSServiceLocal() ;
		HttpSession sess = request.getSession();
		if (action.equals("getForm")) {
			String transnum = request.getParameter("transnum");
			List ret;
			try {
				ret = css.findManuCost(" where transnum1='" + transnum + "'");
				Iterator it=ret.iterator();
				while(it.hasNext())
				{
					ManuCost mc=(ManuCost)it.next();
					mc.setSpecType(parse.parseSpec(mc.getKaiMoSpec()).sort());
					mc.setProcessScheme(gss.getFlow(mc.getKaiMoSpec()).getSchemeId());
				}
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.lang.Float.class, new FloatJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);
				response.getWriter().print(json);
			}
			catch(GSException gse)
			{
				System.out.println("GSException is found in getForm:"+gse.getMessage());
				response.getWriter().print("{success:false}");
			}
			catch (CSException e) {
				// TODO Auto-generated catch block
				System.out.println("getForm error:"+e.getMessage());
	        	response.getWriter().print("{success:false}");
			}

		}
		else if(action.equals("getGrid"))
		{
			String transnum = request.getParameter("transnum");
			List ret;
			try {
				ret = css.findProcsDetail(" where transnum1='" + transnum + "' order by linenum ");
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.lang.Float.class, new FloatJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);
				response.getWriter().print(json);
			} catch (CSException e) {
				// TODO Auto-generated catch block
				System.out.println("getGrid error:"+e.getMessage());
	        	response.getWriter().print("{success:false}");
			}

		}
		else if(action.equals("updateForm"))
		{
			String transnum=request.getParameter("transnum");
		    String getspec=request.getParameter("getSpec");
		    String kaimospec=request.getParameter("kaiMoSpec");
		    String net=request.getParameter("netWeight");
		    String gross=request.getParameter("grossWeight");
		    String grossg=request.getParameter("grossGPrice");
		    String grossp=request.getParameter("grossPrice");
		    String grossu=request.getParameter("grossUpdate");
		    String mtrl=request.getParameter("mtrlProcsPrice");
		    String other=request.getParameter("otherFee");
		    String pack=request.getParameter("packFee");
		    String congci=request.getParameter("congCiFee");
		    String base=request.getParameter("baseCost");
		    String total=request.getParameter("totalUpdate");
		    String amount=request.getParameter("amount");
		    String sxr=request.getParameter("sanXiangRate");
		    String sxf=request.getParameter("sanXiangFee");
		    String taxr=request.getParameter("taxRate");
		    String taxf=request.getParameter("taxFee");
		    String last=request.getParameter("mtrlProcs");
		    String ssign=request.getParameter("ssign");
		    String plate=request.getParameter("plate");
		    try{
		    ManuCost mc = new ManuCost(transnum, kaimospec, getspec,
                    Float.valueOf(net), Float.valueOf(gross),
                    Float.valueOf(grossg),
                    Float.valueOf(grossu),
                    Float.valueOf(grossp),
                    Float.valueOf(mtrl), Float.valueOf(other),
                    Float.valueOf(pack),
                    Float.valueOf(congci),
                    Float.valueOf(base), Float.valueOf(total),
                    Float.valueOf(amount), Float.valueOf(sxr),
                    Float.valueOf(sxf), Float.valueOf(taxr),
                    Float.valueOf(taxf), Float.valueOf(last),ssign,plate);
		    try {
				css.updateManuCost(mc);
		        response.getWriter().print("{success:true}");

			} catch (CSException e) {
		        System.out.println("CSException:"+e.getMessage());
				response.getWriter().print("{success:false}");
			}
		    }
		    catch (NumberFormatException ex) {
		        System.out.println("NumberFormatException:"+ex.getMessage());
		        response.getWriter().print("{success:false}");
		    }
		}

		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here

	}

}
